import { PropsWithChildren, useEffect } from "react";
import { SiderBar } from "../components/SiderBar";
import { useDocGenerationStore } from "../store";
import { DocGenerationIndex } from "./DicGeneration/DocGenerationIndex";
import { DocGenerationInfo } from "./DicGeneration/DocGenerationInfo";
import {
  fetchCreateChat,
  fetchGeneratorText,
  fetchSaveGetGeneratorText,
} from "@/api/server/recommend_question";
import { message } from "antd";

interface IDocGenerationProps {
  className?: string;
}
export function DocGeneration(props: PropsWithChildren<IDocGenerationProps>) {
  const list = useDocGenerationStore((state) => state.list);
  const collapse = useDocGenerationStore((state) => state.collapse);
  const activeKey = useDocGenerationStore((state) => state.activeKey);
  const setActiveKey = useDocGenerationStore((state) => state.setActiveKey);
  const setCollapse = useDocGenerationStore((state) => state.setCollapse);
  const refreshList = useDocGenerationStore((state) => state.refreshList);
  const listType = useDocGenerationStore((state) => state.listType);
  const listSearch = useDocGenerationStore((state) => state.listSearch);
  const setListType = useDocGenerationStore((state) => state.setListType);
  const setListSearch = useDocGenerationStore((state) => state.setListSearch);

  const onSubmit = async (s: string) => {
    const res = await fetchCreateChat({
      user_name: "test",
      sender: "user",
      message: s,
      type: "wenshu",
    });

    const chat_id = res.data.chat_id;

    const res2 = await fetchGeneratorText({
      content: s,
      chat_id,
    });

    const content = res2.data?.result;
    if (!content) {
      message.error("生成内容为空，请重试");
      refreshList();
      return;
    }

    await fetchSaveGetGeneratorText({
      chat_id: chat_id,
      query: s,
      content,
    });

    refreshList();
    setActiveKey(chat_id);
    return;
  };

  useEffect(() => {
    refreshList();
  }, []);

  return (
    <div className="flex flex-row h-full">
      <SiderBar
        type="doc-generation"
        collapse={collapse}
        setListSearch={setListSearch}
        setListType={setListType}
        listSearch={listSearch}
        refreshList={refreshList}
        listType={listType}
        list={list}
        onSetActiveKey={setActiveKey}
        onSetCollapse={setCollapse}
        activeKey={activeKey}
      />
      <div className="flex-1 min-w-0 PageContent flex flex-col items-center">
        {activeKey ? (
          <div className="w-full h-full flex flex-col">
            <DocGenerationInfo infoKey={activeKey} />
          </div>
        ) : (
          <div className="w-[84%] h-full flex flex-col">
            <DocGenerationIndex onSubmit={onSubmit} />
          </div>
        )}
      </div>
    </div>
  );
}
